package com.wans.easyuibackend.service.impl;

import com.wans.easyuibackend.exception.data.DataFormatException;
import com.wans.easyuibackend.mapper.StaffMapper;
import com.wans.easyuibackend.pojo.Result;
import com.wans.easyuibackend.pojo.StaffInfo;
import com.wans.easyuibackend.service.StaffService;
import com.wans.easyuibackend.utils.validation.DataValidation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;

@Service
@SuppressWarnings({"all"})
public class StaffServiceImpl implements StaffService {

    @Autowired
    private StaffMapper staffMapper;
    @Autowired
    private DataValidation dataValidation;

    @Override
    public Object findStaffInfo(Integer page, Integer rows) {
        ArrayList<StaffInfo> staffInfos = staffMapper.findStaffInfo((page - 1) * rows, rows);
        Integer total = staffMapper.findTotal();

        HashMap<String, Object> result = new HashMap<String, Object>();
        result.put("total", total);
        result.put("rows", staffInfos);

        return result;
    }

    @Override
    public Object addStaffInfo(StaffInfo staffInfo) {

        //数据校验
        boolean staffValidation = dataValidation.staffValidation(staffInfo);
        if (!staffValidation) {
            //直接抛出异常，然后全局捕获异常
            throw new DataFormatException("400", "数据异常");
        }

        //数据插入MySQL
        Integer addStaffInfo = staffMapper.addStaffInfo(staffInfo);

        if (addStaffInfo == 0) {
            //数据库未插入数据，这种情况大概率不会出现，未知异常，后续可能添加唯一键导致数据库数据插入失败比如身份证号唯一
            throw new DataFormatException("400", "数据异常");
        }

        return new Result(200, "完成了" + addStaffInfo + "行数据的添加", null);
    }

    @Override
    public Object updateStaffInfo(StaffInfo staffInfo) {

        //数据校验
        boolean staffValidation = dataValidation.staffValidation(staffInfo);
        if (!staffValidation || staffInfo.getStaffId() == null) {
            //直接抛出异常，然后全局捕获异常
            throw new DataFormatException("400", "数据异常");
        }

        //更新数据库
        Integer updated = staffMapper.updateStaffInfo(staffInfo);

        if (updated == 0) {
            //为进行数据更新
            throw new DataFormatException("400", "数据未异常，不知原因数据库未插入数据");
        }

        return Result.success();
    }

    @Override
    @Transactional
    public Object deleteStaffInfo(String ids) {
        if (ids == null || ids.trim().equals("")) {
            //直接抛出异常，然后全局捕获异常
            throw new DataFormatException("400", "数据异常");
        }

        //删除数据
        for (String id : ids.split(",")) {
            Integer deleted = staffMapper.deleteStaffInfo(id);

            if(deleted == 0) {
                //为进行数据更新
                throw new DataFormatException("400", "数据未异常，不知原因数据库未插入数据");
            }
        }

        return Result.success();
    }
}
